import { _decorator, Color, randomRangeInt, UITransform } from 'cc';
import { Game } from './Game';
import { PixelSprite } from './PixelSprite';
const { ccclass, property } = _decorator;


//要和 ShapeSprite 的 texWidth , texHeight 是整数倍关系
const pixelSize: number = 6; //单个方块，划分格子个数6x6

//俄罗斯方块形状
const shapes = [
    [[1, 1, 1, 1]], // I
    [[2, 2], [2, 2]], // O
    [[0, 3, 0], [3, 3, 3]], // T
    [[0, 4, 4], [4, 4, 0]], // S
    [[5, 5, 0], [0, 5, 5]], // Z
    [[6, 0, 0], [6, 6, 6]], // J
    [[0, 0, 7], [7, 7, 7]]  // L
];


@ccclass('ShapeSprite')
export class ShapeSprite extends PixelSprite {


    public shapeID: number = 0; //形状
    public color0Idx: number = 0; //主色
    public color1Idx: number = 0; //副色


    public score: number = 36; //形状，默认得分

    public flags: number[][] = [];
    public colors: Color[][] = [];

    public shapeCol: number = 0;
    public shapeRow: number = 0;

    private uiWidth: number = 0;
    private uiHeight: number = 0;



    //实时ui显示高度
    get hight() {
        let s = this.node.scale;
        return this.uiHeight * s.y;
    }

    //实时ui显示宽度
    get width() {
        let s = this.node.scale;
        return this.uiWidth * s.x;
    }

    get gridsH() {
        return this.shapeRow * pixelSize;
    }

    get gridsW() {
        return this.shapeCol * pixelSize;
    }


    @property
    isDroper: boolean = false;

    // @property({ range: [0, 1], step: 0.01 })
    // 生成双色方块的概率，0 表示永远单色，1 表示所有形状都可能包含副色
    twoColorChance: number = 0.7// 0.4;

    start() {
        super.start();
        if (!this.isDroper) {
            this.nextShape();
        }

    }

    /**
     * 复制形状数据
     * @param shape 形状数据
     */
    copyShape(shape: ShapeSprite) {

        // 深拷贝 flags
        this.flags = [];
        for (let i = 0; i < shape.flags.length; i++) {
            this.flags[i] = [];
            for (let j = 0; j < shape.flags[i].length; j++) {
                this.flags[i][j] = shape.flags[i][j];
            }
        }

        // 深拷贝 colors
        this.colors = [];
        for (let i = 0; i < shape.colors.length; i++) {
            this.colors[i] = [];
            for (let j = 0; j < shape.colors[i].length; j++) {
                this.colors[i][j] = shape.colors[i][j];
            }
        }

        // 更新像素精灵
        this.updateDatas(this.colors, 0, 0, true, true);


        this.uiWidth = shape.uiWidth;
        this.uiHeight = shape.uiHeight;

        this.shapeCol = shape.shapeCol;
        this.shapeRow = shape.shapeRow;

        this.color0Idx = shape.color0Idx;
        this.color1Idx = shape.color1Idx;
        this.score = shape.score;

    }

    /**
     * 旋转90度（顺时针）
     * @param shape 形状数据
     */
    rotateShape(shape: number[][]) {
        const row = shape.length;
        const col = shape[0].length;
        const rotated: number[][] = [];
        for (let x = 0; x < col; x++) {
            rotated[x] = [];
            for (let y = row - 1; y >= 0; y--) {
                rotated[x][row - 1 - y] = shape[y][x];
            }
        }
        shape.length = 0;
        for (let i = 0; i < rotated.length; i++) {
            shape.push(rotated[i]);
        }
    }

    /**
     * 水平翻转
     * @param shape 形状数据
     */
    flipShapeX(shape: number[][]) {
        for (let y = 0; y < shape.length; y++) {
            shape[y].reverse();
        }
    }


    nextShape() {

        this.shapeID = randomRangeInt(0, shapes.length);

        let shape = shapes[this.shapeID].slice();

        this.score = 36; //形状的得分

        if (this.shapeID) {
            //竖向方块的1/4概率;
            if (Math.random() > 0.75) {
                this.rotateShape(shape);
            }
        }

        let mainIdx = 0; //主色id
        let otherIdx = 0;//副色id
        let otherCount = 1; //副色个数

        //最大颜色个数
        let maxColor = Game.instance.randColors.length;
        mainIdx = randomRangeInt(0, maxColor);
        otherIdx = randomRangeInt(0, maxColor);
        if (otherIdx == mainIdx) {
            otherIdx = mainIdx + randomRangeInt(0, maxColor - 1);
            otherIdx = otherIdx % maxColor;
        }


        this.color0Idx = mainIdx;
        this.color1Idx = otherIdx;

        //方块实际格子大小
        let hight = shape.length;
        let width = shape[0].length;

        // 是否使用副色（双色），按概率决定
        let useTwoColors = Math.random() < this.twoColorChance;
        // 副色在形状像素中出现的概率（可进一步暴露为属性）
        let secondaryProb = 0.45;

        for (let i = 0; i < hight; i++) {
            for (let j = 0; j < width; j++) {
                if (shape[i][j] > 0) {
                    if (useTwoColors && Math.random() < secondaryProb) {
                        shape[i][j] = otherIdx + 1; // 使用副色
                    } else {
                        shape[i][j] = mainIdx + 1; // 使用主色
                    }
                }
            }
        }


        this.setShapeData(shape);
    }


    shapeCenter(row: number, col: number, w: number, h: number) {

        //修正居中
        let s = this.node.getWorldScale();
        let t = this.node.getComponent(UITransform).contentSize;
        let offsety = -s.y * ((h - row) * 0.5 / h) * t.height;
        let offsetx = s.x * ((w - col) * 0.5 / w) * t.width;
        this.node.setPosition(offsetx, offsety);

        //ui显示区域大小
        this.uiHeight = (1.0 * row * t.height / h);
        this.uiWidth = (1.0 * col * t.width / w);

        //实际形状行列大小
        this.shapeRow = row;
        this.shapeCol = col;
    }


    setShapeData(shape: number[][]) {

        let size = pixelSize;
        //方块实际格子大小
        let row = shape.length;
        let col = shape[0].length;

        let ZERO = new Color(0, 0, 0, 0);
        //显示精灵实际格子大小
        let w = Math.round(this.texWidth / size);
        let h = Math.round(this.texHeight / size);
        this.shapeCenter(row, col, w, h);//修正形状显示居中

        let randColors = Game.instance.randColors; //随机颜色模板

        for (let i = 0; i < h; i++) {
            for (let k = 0; k < size; k++) {
                this.colors[i * size + k] = [];
                this.flags[i * size + k] = [];
            }

            for (let j = 0; j < w; j++) {
                let idx = 0;
                if (i < row && j < col) {
                    idx = shape[i][j];
                }

                for (let n = 0; n < size; n++) {
                    for (let m = 0; m < size; m++) {
                        this.flags[i * size + n][j * size + m] = idx;
                        this.colors[i * size + n][j * size + m] = ZERO;
                        if (idx > 0) {
                            let color = randColors[idx - 1][randomRangeInt(0, 100)]; //随机碎色
                            this.colors[i * size + n][j * size + m] = color;
                        }
                    }
                }
            }
        }

        //上传像素数据到纹理
        this.updateDatas(this.colors, 0, 0, true, true);

    }

}


